package com.warm.pump.executor.batch;

import com.warm.pump.frame.gen.util.TypeCast;
import com.warm.pump.module.work.bean.po.gen.WorkItem;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class CursorRedisWriter implements ItemWriter<Object> {
    private static final Logger log = LoggerFactory.getLogger(CursorRedisWriter.class);
    private WorkItem itemDtl;
    @Autowired
    private RedisTemplate redisTemplate;

    private boolean fail = false;

    public void setFail(boolean fail) {
        this.fail = fail;
    }

    /**
     * @see ItemWriter#write(List)
     */
    public void write(List<? extends Object> data) throws Exception {

        String[] cacheKeyFields = itemDtl.getCacheKeyField().split(",");
        //Map<String,Object> redisMap = new HashMap<>();
        for (int i = 0; i < data.size(); i++) {
            Map<String, Object> resultMap = (Map<String, Object>) data.get(i);
            //redisMap.put(TypeCast.getString(resultMap.get(itemDtl.getCacheKeyField())),resultMap);

            String cacheKey = "";
            int j = 1;
            for (String cacheField : cacheKeyFields) {
                if (StringUtils.isNotEmpty(cacheField)) {
                    cacheKey += TypeCast.getString(resultMap.get(cacheField));
                    if (j < cacheKeyFields.length) {
                        cacheKey += "-";
                    }
                }
                j++;
            }

            redisTemplate.opsForHash().put(itemDtl.getCacheName(), cacheKey, resultMap);
        }
        // redisTemplate.opsForHash().putAll(itemDtl.getCacheName(),redisMap);
        redisTemplate.expire(itemDtl.getCacheName(), itemDtl.getExpireTime(), TimeUnit.SECONDS);

        //redisMap.clear();
        log.debug("[{}],write{}行数据", itemDtl.getItemName(), data.size());
        if (fail) {
            throw new RuntimeException("Planned failure");
        }
    }


    public WorkItem getItemDtl() {
        return itemDtl;
    }

    public void setItemDtl(WorkItem itemDtl) {
        this.itemDtl = itemDtl;
    }
}